package site.abely.util;


import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class UrlUtils {
    private static Joiner joiner = Joiner.on("&").skipNulls();

    public static Map<String, String> explainURLParams(String params) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = null;
        // 每个键值为一组
        arrSplit = params.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            // 解析出键值
            if (arrSplitEqual.length > 1) {
                // 正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    // 只有参数没有值，加入空字符
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    public static String buildURLParams(Map<String, String> params) {
        if (Objects.equal(null, params) || params.isEmpty()) {
            return "";
        }
        List<String> paramList = Lists.transform(Lists.newArrayList(params.entrySet()), new Function<Map.Entry<String, String>, String>() {
            public String apply(Map.Entry<String, String> entry) {
                StringBuffer sb = new StringBuffer();
                sb.append(entry.getKey()).append("=").append(entry.getValue());
                return sb.toString();
            }
        });
        return joiner.join(paramList);
    }

    public static String appendParams(String url, Map<String, String> params) {
        StringBuffer sb = new StringBuffer(url);
        if (sb.indexOf("?") > 0) {
            sb.append("&");
            sb.append(buildURLParams(params));
        } else {
            sb.append("?");
            sb.append(buildURLParams(params));
        }
        return sb.toString();
    }

}
